package com.chc.util;

import static com.chc.util.Constant.KEY_LANG_BASE_NAME;

import java.io.IOException;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.map.ObjectMapper;

import com.chc.finance.sys.vo.User;


public class WebUtil {
	public static final Log log=LogFactory.getLog(WebUtil.class);
	
	public static void goToErrorPage(HttpServletRequest request, HttpServletResponse response, Exception e) throws IOException {
		request.setAttribute("expStr", e.getMessage());
		response.sendRedirect("error.jsp");
	}
	
	public static void writeJsonStr(HttpServletResponse resp, Object obj) throws IOException {
		String re = writeJsonStr(obj);
		resp.setContentType("application/json;charset=utf-8");
		resp.getWriter().println(re);
	}
	
	public static String writeJsonStr(Object obj) throws IOException {
		return new ObjectMapper().writeValueAsString(obj);
	}
	
	public static User getCurrentUser(HttpServletRequest req){
		return (User)req.getSession().getAttribute(Constant.KEY_USER_INFO);
	}

	public static void writeJsonStr(HttpServletRequest req, HttpServletResponse resp, ServiceResult r) throws IOException {
		if(r.getMsgCode() != null && !"".equals(r.getMsgCode())) {
			r.setMsg(ResourceBundle.getBundle(KEY_LANG_BASE_NAME, req.getLocale()).getString(r.getMsgCode()));
		}
		
		writeJsonStr(resp, r);
	}
	
}
